using System.Linq;
using Myotragus.Data.Domain;
using Myotragus.Data.Metadata;
using Myotragus.Data.Util;
using NHibernate;

namespace Myotragus.Data.Criteria
{
	public static class LocalizableQueryBuilderHelper
	{
		public static void SetDefaultLcId<TEntity>(ISession session, object id, 
			int lcId, ILocalizableEntityDescriptor<TEntity> descriptor) 
			where TEntity : IEntity
		{
			var save = session.Get(descriptor.SaveEntityImplementation, id);

			UpdateTexts(save, lcId, descriptor);
			SaveChanges(session, save);

			session.Flush();
		}

		public static void SaveChanges(ISession session, object save)
		{
			using (var transaction = session.BeginTransaction())
			{
				session.Save(save);
				transaction.Commit();
			}
		}

		public static void UpdateTexts<TEntity>(object save, int lcId, 
			ILocalizableEntityDescriptor<TEntity> descriptor) where TEntity : IEntity
		{
			foreach (var text in descriptor.LocalizableProperties
				.Select(prop => (DefaultsSaveLocalizableText)descriptor
					.SaveEntityProperties[prop].GetValue(save, ReflectionHelper.EmptyObjects)))
			{
				text.DefaultLcId = lcId;
			}
		}
	}
}